<template>
  <div class="prop-log-container">
    <div class="search-section">
      <div class="search-title">搜索信息</div>
      
      <div class="search-form">
        <el-form :inline="true" size="small" :model="searchForm">
          <el-form-item label="用户ID">
            <el-input v-model="searchForm.uid" placeholder="请输入用户ID" style="width: 200px;" type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="来源">
            <el-select v-model="searchForm.source" placeholder="任意" style="width: 150px;">
              <el-option label="任意" :value="0"></el-option>
              <el-option label="赠送" :value="1"></el-option>
              <el-option label="充值" :value="2"></el-option>
              <el-option label="其他" :value="3"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="渠道">
            <el-select v-model="searchForm.channel" placeholder="请选择渠道" style="width: 150px;" clearable>
              <el-option
                v-for="item in channelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="时间">
            <el-date-picker
              v-model="searchForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              style="width: 380px;">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>道具日志</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportData"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>
      
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="id" label="ID" width="70" sortable></el-table-column>
        <el-table-column prop="uid" label="UUID" width="100"></el-table-column>
        <el-table-column prop="source" label="来源" width="150">
          <template slot-scope="scope">
            {{ getSourceText(scope.row.source) }}
          </template>
        </el-table-column>
        <el-table-column prop="change_coin" label="变动金额" width="150" sortable>
          <template slot-scope="scope">
            <span :style="scope.row.change_coin < 0 ? 'color: #F56C6C;' : 'color: #67C23A;'">
              {{ formatNumberWithCommas(scope.row.change_coin) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="before_coin" label="变动前金额" width="150" sortable>
          <template slot-scope="scope">
            {{ formatNumberWithCommas(scope.row.before_coin) }}
          </template>
        </el-table-column>
        <el-table-column prop="after_coin" label="变动后金额" width="150" sortable>
          <template slot-scope="scope">
            {{ formatNumberWithCommas(scope.row.after_coin) }}
          </template>
        </el-table-column>
        <el-table-column prop="bet" label="倍率/下注额" width="120" sortable>
          <template slot-scope="scope">
            {{ formatNumberWithCommas(scope.row.bet) }}
          </template>
        </el-table-column>
        <el-table-column prop="total_play" label="总玩" width="100" sortable></el-table-column>
        <el-table-column prop="total_win" label="总赢" width="100" sortable></el-table-column>
        <el-table-column prop="real_coin" label="真实金币" width="150" sortable>
          <template slot-scope="scope">
            {{ formatNumberWithCommas(scope.row.real_coin) }}
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="170" sortable></el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { playerCoinRecord } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'PropLog',
  mixins: [channelMixin],
  data() {
    return {
      searchForm: {
        uid: '',
        channel: null,
        source: '',
        timeRange: [
          this.getLastMonthDate(),
          new Date()
        ]
      },
      tableData: [],
      loading: false,
      exportLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0
    };
  },
  
  async created() {
    // 渠道选项通过mixin自动加载
    this.fetchData()
  },
  
  methods: {
    getLastMonthDate() {
      const date = new Date();
      date.setMonth(date.getMonth() - 1);
      return date;
    },
    formatNumberWithCommas(number) {
      if (number === null || number === undefined) return '';
      return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    },
    getSourceText(source) {
      const sourceMap = {
        1: '赠送',
        2: '充值', 
        3: '游戏',
        // 可以根据实际接口文档添加更多映射
      }
      return sourceMap[source] || '未知'
    },
    async fetchData() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          uid: this.searchForm.uid ? parseInt(this.searchForm.uid) : 0,
          source: this.searchForm.source || 0,
          channel: this.formatChannelParam(this.searchForm.channel)
        }
        
        // 如果有时间范围，添加时间参数
        if (this.searchForm.timeRange && this.searchForm.timeRange.length === 2) {
          params.begin_time = this.searchForm.timeRange[0]
          params.end_time = this.searchForm.timeRange[1]
        }
        
        console.log('===== PropLog Debug Info =====')
        console.log('发送参数:', params)
        
        const response = await playerCoinRecord(params)
        console.log('接口返回完整数据:', response)
        console.log('response类型:', typeof response)
        console.log('response.data类型:', typeof response.data)
        
        // 检查响应是否存在
        if (!response) {
          console.error('response为空')
          this.$message.error('接口返回数据为空')
          return
        }
        
        // 处理各种可能的成功状态码
        const isSuccess = response.code === 0 || response.code === '0' || 
                         response.status === 200 || response.status === '200' ||
                         !response.code // 有些接口可能不返回code字段
        
        console.log('判断是否成功:', isSuccess, '原始code:', response.code)
        
        if (isSuccess && response.data !== undefined) {
          console.log('开始解析数据...')
          console.log('response.data:', response.data)
          console.log('response.data是否为数组:', Array.isArray(response.data))
          
          // 尝试多种可能的数据结构
          let records = []
          
          // 情况1: response.data.records
          if (response.data && response.data.records && Array.isArray(response.data.records)) {
            records = response.data.records
            console.log('使用response.data.records:', records.length)
          }
          // 情况2: response.data.list  
          else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            records = response.data.list
            console.log('使用response.data.list:', records.length)
          }
          // 情况3: response.data 本身就是数组
          else if (Array.isArray(response.data)) {
            records = response.data
            console.log('使用response.data直接作为数组:', records.length)
          }
          // 情况4: response.data.data
          else if (response.data && response.data.data && Array.isArray(response.data.data)) {
            records = response.data.data
            console.log('使用response.data.data:', records.length)
          }
          // 情况5: response本身是数组
          else if (Array.isArray(response)) {
            records = response
            console.log('使用response直接作为数组:', records.length)
          }
          // 情况6: response.records
          else if (response.records && Array.isArray(response.records)) {
            records = response.records
            console.log('使用response.records:', records.length)
          }
          // 情况7: response.list
          else if (response.list && Array.isArray(response.list)) {
            records = response.list
            console.log('使用response.list:', records.length)
          }
          else {
            console.warn('未找到合适的数据数组, response.data结构:', response.data)
            // 如果response.data是对象，尝试找第一个数组字段
            if (response.data && typeof response.data === 'object') {
              for (const key in response.data) {
                if (Array.isArray(response.data[key])) {
                  records = response.data[key]
                  console.log(`使用response.data.${key}:`, records.length)
                  break
                }
              }
            }
          }
          
          console.log('最终解析的records:', records)
          console.log('records长度:', records.length)
          
          // 如果有数据，打印第一条记录的结构
          if (records.length > 0) {
            console.log('第一条记录结构:', records[0])
            console.log('第一条记录的字段:', Object.keys(records[0]))
          }
          
          this.tableData = records
          
          // 处理总数 - 尝试多种可能的total字段
          let total = 0
          if (response.data && response.data.total_page) {
            total = response.data.total_page * this.pageSize
          } else if (response.data && response.data.total) {
            total = response.data.total
          } else if (response.total_page) {
            total = response.total_page * this.pageSize
          } else if (response.total) {
            total = response.total
          } else {
            total = records.length
          }
          
          this.total = total
          
          console.log('设置tableData长度:', this.tableData.length)
          console.log('设置total:', this.total)
          console.log('===== Debug Info End =====')
          
          // 强制触发视图更新
          this.$nextTick(() => {
            this.$forceUpdate()
          })
          
        } else {
          console.error('接口返回错误或无数据:', response)
          this.$message.error(response.msg || response.message || response.error || '获取数据失败')
        }
      } catch (error) {
        console.error('获取道具日志失败:', error)
        this.$message.error('获取数据失败: ' + error.message)
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchData();
    },
    handleReset() {
      this.searchForm = {
        uid: '',
        channel: null,
        source: '',
        timeRange: [
          this.getLastMonthDate(),
          new Date()
        ]
      };
      this.handleSearch();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    async exportData() {
      this.exportLoading = true
      try {
        const params = {
          page: 1,
          page_size: 10000,
          uid: this.searchForm.uid ? parseInt(this.searchForm.uid) : 0,
          source: this.searchForm.source || 0,
          channel: this.formatChannelParam(this.searchForm.channel)
        }
        
        if (this.searchForm.timeRange && this.searchForm.timeRange.length === 2) {
          params.begin_time = this.searchForm.timeRange[0]
          params.end_time = this.searchForm.timeRange[1]
        }
        
        const response = await playerCoinRecord(params)
        const allData = response.data.records || []
        
        const columns = [
          { prop: 'id', label: 'ID' },
          { prop: 'uid', label: 'UUID' },
          { prop: 'source', label: '来源', formatter: (row) => this.getSourceText(row.source) },
          { prop: 'change_coin', label: '变动金额' },
          { prop: 'before_coin', label: '变动前金额' },
          { prop: 'after_coin', label: '变动后金额' },
          { prop: 'bet', label: '倍率/下注额' },
          { prop: 'total_play', label: '总玩' },
          { prop: 'total_win', label: '总赢' },
          { prop: 'real_coin', label: '真实金币' },
          { prop: 'create_time', label: '创建时间' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `道具日志_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    },
    handlePrint() {
      window.print();
    },
    refreshTable() {
      this.fetchData();
      this.$message({
        type: 'success',
        message: '数据已刷新'
      });
    }
  }
};
</script>

<style scoped>
.prop-log-container {
  padding: 20px;
  background-color: #fff;
}

.search-section {
  margin-bottom: 20px;
  padding: 10px 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.search-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.table-section {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  padding: 10px 20px;
}

.table-options {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.left-buttons {
  display: flex;
  align-items: center;
}

.right-buttons {
  display: flex;
  align-items: center;
}

.right-buttons .el-button {
  margin-left: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 